# -*- coding:utf-8 -*-
import json
import traceback

# @Time    : 2023/12/13 07:05
# @Author  : yaodong
# @Email   : zengwenjia@lingxi.ai
# @File    : QWRobotProcess.py
# @Email   : yaodong@lingxi.ai
# @File    : QWRobotCallBackProcess.py
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

# 用于处理企微渠道机器人相关服务
from bot.insurance_planner_gpt.qw_server.common import wework_constants
from db.redis.redis_service import RedisMemory

from common.log import logger

redis_memory = RedisMemory()
acquire_robot_key = wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "acquire_robot:"


class QWRobotCallBackProcess:

    def __init__(self, company_id, event_type, robot_id, req_id, message) -> None:
        self.event_type = event_type
        self.robot_id = robot_id
        self.company_id = company_id
        self.req_id = req_id
        self.data = message.get("data", {})

    async def process_all_event_type(self):
        if wework_constants.WEWORK_EVENT_TYPE_GET_ROBOT_LIST == self.event_type:
            await self.get_robot_list()
        elif wework_constants.WEWORK_EVENT_TYPE_ROBOT_LOG_OUT == self.event_type:
            await self.robot_log_out()
        elif wework_constants.WEWORK_EVENT_TYPE_ROBOT_LOGIN_SUCCESS == self.event_type:
            await self.robot_login()

    async def robot_log_out(self):
        logger.info(f"机器人[{self.robot_id}]登出")
        redis_memory.srem(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "robot:" + str(self.company_id), self.robot_id)

    async def robot_login(self):
        logger.info(f"机器人[{self.robot_id}]登录成功")
        redis_memory.sadd(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "robot:" + str(self.company_id), self.robot_id)

    async def get_robot_list(self):

        robot_list = self.data.get("robot_list", [])
        redis_memory.delete(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "robot:" + str(self.company_id))
        if robot_list:
            cache_dict = {}
            for robot in robot_list:
                login_status = robot.get("login_status", 2)
                robot_id = robot.get('robot_id', '')

                if login_status == wework_constants.ROBOT_LOGIN_STATUS_LOGIN and robot_id:
                    cache_dict[str(robot_id)] = robot.get('name', '')
                    redis_memory.sadd(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "robot:" + str(self.company_id),
                                      robot_id)
                    logger.info("同步全部的机器人列表完成")

            if cache_dict:
                idNameKey = wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "robot_info:" + str(
                    self.company_id)
                logger.info('缓存在线企微信息：{},{}'.format(idNameKey,cache_dict))
                redis_memory.delete(idNameKey)
                redis_memory.set(idNameKey, json.dumps(cache_dict,ensure_ascii=False))


def get_addwechat_robot(company_id,user_name=None):
    robot_id = None
    if user_name:
        robot_id = get_addwechat_robot_by_username(company_id,user_name)
        if not robot_id:
            logger.info('未找到座席【{}】名下的企微，从公共池查找'.format(user_name))
            robot_id = redis_memory.rpop(acquire_robot_key + str(company_id))
            if robot_id:
                redis_memory.lpushall(acquire_robot_key + str(company_id),[robot_id])
            else:
                logger.error("[{}] 获取不到加微坐席".format(company_id))
    elif not user_name:
        robot_id = redis_memory.rpop(acquire_robot_key + str(company_id))
        if not robot_id:
            robot_list = redis_memory.smembers(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "robot:" + str(company_id))
            if robot_list:
                redis_memory.lpushall(acquire_robot_key + str(company_id), list(robot_list))
                robot_id = redis_memory.rpop(acquire_robot_key + str(company_id))
                return robot_id
            else:
                logger.error("获取不到加微坐席")

    return robot_id

def get_addwechat_robot_by_username(company_id,user_name):
    robot_id = None
    try:
        userNameKey = str(user_name).split('@')[0]
        redisKey = wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "username_add_wechat:" + str(
            company_id) + ":" + userNameKey
        logger.info('get_robot_id_by_name:{}'.format(redisKey))
        robot_id = redis_memory.rpop(redisKey)
        if robot_id:
            redis_memory.lpushall(redisKey, [robot_id])
    except Exception as ee:
        logger.error(traceback.format_exc())
    return robot_id


if __name__ == '__main__':
    print(get_addwechat_robot_by_username('2252','fangcheng@lingxi.ai'))
